package cn.liuwenlin.mq.activemqspringboot.service;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.network.jms.SimpleJmsMessageConvertor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jms.JmsProperties;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.SimpleMessageConverter;
import org.springframework.stereotype.Service;

import javax.jms.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 276834
 */
@Service
public class SenderServiceImpl implements MessagePublishService {

    /**
     * spring包装好的消息模板，发送简单消息比较快速
     */
    @Autowired
    private JmsMessagingTemplate messagingTemplate;

    /**
     * spring原始的jms消息模板， 可以灵活的自定义消息类型
     */
    @Autowired
    private JmsTemplate template;

    @Override
    public void sendTopic(String destination,String msg) throws JMSException {
        //自定义获取连接工厂，创建连接，然后后续操作就按照原始的jms处理步骤操作
        ConnectionFactory connectionFactory = template.getConnectionFactory();
        Connection connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, JmsProperties.AcknowledgeMode.AUTO.getMode());
        Topic topic = session.createTopic(destination);
        MessageProducer producer = session.createProducer(topic);

        TextMessage textMessage = session.createTextMessage();
        textMessage.setText("this is self define topic text message");
        producer.send(textMessage);

        /**
         * 自定义类型数据创建
         */
        template.send(destination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
//                session.createTopic("springboot");
                TextMessage textMessage = session.createTextMessage(msg);
                return textMessage;
            }
        });
    }

    @Override
    public void sendToQueue(String destination,String msg) throws JMSException {
        List<String> list = new ArrayList<>();
        list.add("jack");
        list.add("tony");
        list.add("babe");
        //设置消息格式化转换器
//        messagingTemplate.setJmsMessageConverter(new SimpleMessageConverter());
//        messagingTemplate.convertAndSend(new ActiveMQQueue(destination), list.toString());
        messagingTemplate.convertAndSend(new ActiveMQQueue(destination), list);
    }

    @Override
    public void send(String destination, String msg) throws JMSException {
        messagingTemplate.convertAndSend(destination, msg);
    }
}
